namespace Backoffice.Domain.Entities.App;
/// <summary>
/// 系统用户实体
/// </summary>
/// 
public class AppUser : EntityBase
    {
    
        public string Username { get; private set; }
        public string Email { get; private set; }
        public string? Phone { get; set; }
        public string PasswordHash { get; private set; }
        public DateTime LastLoginAt { get; private set; }

        // 用户角色导航属性
        public virtual List<AppUserRole> UserRoles { get; private set; } = new();
    


    //构造函数
#pragma warning disable CS8618 // 在退出构造函数时，不可为 null 的字段必须包含非 null 值。请考虑添加 "required" 修饰符或声明为可为 null。
    public AppUser() {}
#pragma warning restore CS8618 // 在退出构造函数时，不可为 null 的字段必须包含非 null 值。请考虑添加 "required" 修饰符或声明为可为 null。

    public AppUser(string username,  string passwordHash,string email,string phone)

    {
            Username = username;
            Email = email;
            PasswordHash = passwordHash;
            LastLoginAt = DateTime.UtcNow;
            Phone=phone;
        }

        public void UpdateInfo(string username, string email,string phone)
        {
            Username = username;
            Email = email;
            Phone = phone;

            
        }

        public void ChangePassword(string newHash)
        {
            if (string.IsNullOrEmpty(newHash))
            throw new ArgumentNullException(nameof(newHash));

        PasswordHash = newHash;
        UpdatedAt = DateTime.UtcNow;
       
        }

        public void AssignRole(AppRole role)
        {
            if (!UserRoles.Any(ur => ur.RoleId == role.Id))
            {
                UserRoles.Add(new AppUserRole(this, role));
            }
        }

        public void RemoveRole(Guid roleId)
        {
            var userRole = UserRoles.FirstOrDefault(ur => ur.RoleId == roleId);
            if (userRole != null)
            {
                UserRoles.Remove(userRole);
            }
        }
        

    }